package vivek.project.pocketmoney.investments.model
{
	import flash.data.*;
	import flash.errors.*;
	import flash.events.Event;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.core.UIComponent;
	
	import vivek.project.pocketmoney.admin.model.AdminConstants;
	import vivek.project.pocketmoney.admin.model.AdminDataCache;
	import vivek.project.pocketmoney.admin.model.AdminDataModel;
	import vivek.project.pocketmoney.common.CommonData;
	import vivek.project.pocketmoney.common.PocketmoneyDataInterface;
	import vivek.project.pocketmoney.common.events.CommonEvents;
	import vivek.project.pocketmoney.common.interfaces.*;
	import vivek.project.pocketmoney.common.logger.PMLogger;
	import vivek.project.pocketmoney.common.utils.CommonConstants;
	import vivek.project.pocketmoney.expenses.events.ExpenseEvent;
	import vivek.project.pocketmoney.expenses.model.ExpenseDataModel;
	import vivek.project.pocketmoney.investments.scripts.InvestmentSQLScript;
	import vivek.project.pocketmoney.investments.scripts.PropertySQLScript;

	public class PropertyDataModel extends UIComponent implements PocketmoneyDataInterface
	{
		private static var instance:PropertyDataModel;
		public static function getInstance():PropertyDataModel
		{
			if (!instance)
			{
				instance=new PropertyDataModel();
			}
			return instance;
		}
		public function PropertyDataModel():void
		{
			loadData();
			edm.addEventListener(CommonEvents.PROPERTY_EXPENSE_TRANSACTION_DELETED, deletePaymentsOnEvent);
		}
		private function deletePaymentsOnEvent(event:ExpenseEvent):void
		{
			var _sqlConnection:SQLConnection=CommonData.getConnection();
			deletePayment(event.data, _sqlConnection);
			_sqlConnection.close();
		}
		private var edm:ExpenseDataModel=ExpenseDataModel.getInstance();
		public function addNewProperty(propertyObj:Object):int
		{
			var _sqlConnection:SQLConnection=CommonData.getConnection();
			//_sqlConnection.open();
			try
			{
				var _statement:SQLStatement=new SQLStatement();
				_statement.sqlConnection=_sqlConnection;
				_sqlConnection.begin();
				_statement.text=PropertySQLScript.ADD_NEW_PROPERTY;
				_statement.parameters[":pd_propertyname"]=propertyObj.propertyName;
				_statement.parameters[":pd_developer"]=propertyObj.developer;
				_statement.parameters[":pd_size"]=propertyObj.size;
				_statement.parameters[":pd_rate"]=propertyObj.rate;
				_statement.parameters[":pd_othercharges"]=propertyObj.charges;
				_statement.parameters[":pd_remark"]=propertyObj.remark;
				_statement.execute();
				_sqlConnection.commit();
				_sqlConnection.close();
				loadData();
				dispatchEvent(new Event("PROPERTYADDED"));
			}
			catch (sqlError:SQLError)
			{
				_sqlConnection.rollback();
				_sqlConnection.close();
					//Alert.show(sqlError.details);
			}
			return 1;
		}
		public function addPropertyPayment(propertyPaymentObj:Object):int
		{
			var _sqlConnection:SQLConnection=CommonData.getConnection();
			//_sqlConnection.open();
			try
			{
				var randomId:Number=new Number();
				randomId=Math.round(Math.random() * 1000000000);
				var _statement:SQLStatement=new SQLStatement();
				_statement.sqlConnection=_sqlConnection;
				_sqlConnection.begin();
				_statement.text=PropertySQLScript.ADD_NEW_PROPERTY_TRANSACTION;
				_statement.parameters[":pp_propertyid"]=propertyPaymentObj.propertyid;
				_statement.parameters[":pp_accountid"]=propertyPaymentObj.accountid;
				_statement.parameters[":pp_amount"]=propertyPaymentObj.amount;
				_statement.parameters[":pp_paymenttype"]=1; // propertyPaymentObj.paymenttype; 
				_statement.parameters[":pp_paymentdate"]=propertyPaymentObj.paymentDate;
				_statement.parameters[":pp_remarks"]=propertyPaymentObj.remark;
				_statement.parameters[":pp_txntype"]=propertyPaymentObj.txnType;
				_statement.parameters[":pp_instru"]=propertyPaymentObj.instru;
				_statement.parameters[":pp_transactionid"]=randomId;
				_statement.parameters[":USER_ID"]=AdminDataCache.ACCOUNT_IN_USE;
				_statement.execute();
				var expRecord:Object=new Object();
				expRecord.userid=AdminDataModel.getInstance().getAccountForId(propertyPaymentObj.accountid).am_userid;
				if (propertyPaymentObj.txnType == CommonConstants.BUY)
				{
					expRecord.type=CommonConstants.BUY; //The money need to be withdrawan from the account
					//	expRecord.account=CommonConstants.PROPERTY_ACCOUNTID;
					expRecord.memo="Property Bought";
						//expRecord.transferAccount=propertyPaymentObj.accountid;
				}
				else
				{
					expRecord.memo="Property Sold";
					expRecord.type=CommonConstants.SELL;
						//expRecord.transferAccount=CommonConstants.PROPERTY_ACCOUNTID;
				}
				expRecord.account=propertyPaymentObj.accountid;
				expRecord.amount=propertyPaymentObj.amount;
				expRecord.category=CommonConstants.PROPERTY_CATEGORY_ID;
				expRecord.payee=0;
				//expRecord.memo="Property Bought/Sold";
				expRecord.date=propertyPaymentObj.paymentDate;
				//expRecord.transferAccount=CommonConstants.;
				expRecord.exRate=1.0;
				edm.addDependentExpenseRecord(expRecord, randomId, _sqlConnection);
				//edm.addDependentTransferRecord(expRecord, randomId, _sqlConnection);
				_sqlConnection.commit();
				_sqlConnection.close();
				loadData();
				edm.refreshExpenseDataCache(null);
				dispatchEvent(new Event("PropertyPaymentAdded"));
			}
			catch (sqlError:SQLError)
			{
				_sqlConnection.rollback();
				_sqlConnection.close();
					//Alert.show(sqlError.details);
			}
			return 1;
		}
		public function deleteSelectedPayments(bullionObj:Array):void
		{
			var _sqlConnection:SQLConnection=CommonData.getConnection();
			_sqlConnection.begin();
			for each (var obj:Object in bullionObj)
			{
				deletePayment(obj, _sqlConnection);
			}
			_sqlConnection.commit();
			edm.refreshExpenseDataCache(null);
			loadData();
			dispatchEvent(new Event("PropertyPaymentDeleted"));
		}
		public function deletePayments(bullionObj:Array):void
		{
			var _sqlConnection:SQLConnection=CommonData.getConnection();
			_sqlConnection.begin();
			for each (var obj:Object in bullionObj)
			{
				deletePayment(obj.pp_transactionid, _sqlConnection);
			}
			_sqlConnection.commit();
			edm.refreshExpenseDataCache(null);
			loadData();
			dispatchEvent(new Event("InvestmentDeleted"));
		}
		public function deletePayment(obj:Object, _sqlConnection:SQLConnection):int
		{
			//_sqlConnection.open();
			try
			{
				var _statement:SQLStatement=new SQLStatement();
				_statement.sqlConnection=_sqlConnection;
				_statement.text=PropertySQLScript.DELETE_PROPERTY_PAYMENT;
				_statement.parameters[":PP_TRANSACTIONID"]=obj.pp_transactionid;
				_statement.execute();
				edm.deleteDependentExpense(obj.pp_transactionid, true, _sqlConnection,obj);
			}
			catch (sqlError:SQLError)
			{
				_sqlConnection.rollback();
					//Alert.show(sqlError.details);
			}
			return 1;
		}
		public function deleteProperties(propertyObj:Array):void
		{
			var _sqlConnection:SQLConnection=CommonData.getConnection();
			_sqlConnection.begin();
			for each (var obj:Object in propertyObj)
			{
				deleteProperty(obj.pd_propertyid, _sqlConnection);
			}
			_sqlConnection.commit();
			edm.refreshExpenseDataCache(null);
			loadData();
			dispatchEvent(new Event("InvestmentDeleted"));
		}
		public function deleteProperty(propertyId:int, _sqlConnection:SQLConnection):int
		{
			//_sqlConnection.open();
			try
			{
				var _statement:SQLStatement=new SQLStatement();
				_statement.sqlConnection=_sqlConnection;
				_statement.text=PropertySQLScript.DELETE_PROPERTY;
				_statement.parameters[":pd_propertyid"]=propertyId;
				var propertyPayements:Array=getPropertyPayments(propertyId)
				_statement.execute();
				//TODO:check
				for each (var o:Object in propertyPayements)
					deletePayment(propertyPayements, _sqlConnection);
			}
			catch (sqlError:SQLError)
			{
				_sqlConnection.rollback();
					//Alert.show(sqlError.details);
			}
			return 1;
		}
		public function getInvestmentTypeName(investmentTypeId:int):String
		{
			for each (var o:Object in InvestmentDataCache.investmentTypeData)
			{
				if (o.it_investmenttypeid == investmentTypeId)
					return o.it_investmenttypename;
			}
			return "";
		}
		public function getPropertyPayments(propertyId:int):Array
		{
			var payments:Array=new Array();
			for each (var o:Object in PropertyDataCache.propertyTransactionData)
			{
				if (o.pp_propertyid == propertyId)
					payments.push(o);
			}
			return payments;
		}
		public function loadData():void
		{
			var _statement:SQLStatement=new SQLStatement();
			var _sqlConnection:SQLConnection=CommonData.getConnection();
			//_sqlConnection.open();
			_statement.sqlConnection=_sqlConnection;
			_statement.text=PropertySQLScript.GET_ALL_PROPERTY;
			_statement.execute();
			PropertyDataCache.propertyData.source=_statement.getResult().data;
			_statement.text=PropertySQLScript.GET_ALL_PROPERTY_TRANSACTIONS;
			_statement.execute();
			PropertyDataCache.propertyTransactionData.source=_statement.getResult().data;
			_sqlConnection.close();
		}
		public function updateFixedIncomeTransaction(fixedIncomeObj:Object):int
		{
			var _sqlConnection:SQLConnection=CommonData.getConnection();
			try
			{
				//_sqlConnection.open();
				var _statement:SQLStatement=new SQLStatement();
				_statement.sqlConnection=_sqlConnection;
				_sqlConnection.begin();
				_statement.text=InvestmentSQLScript.UPDATE_FIXED_INCOME_TRANSACTION;
				_statement.parameters[":fm_investmentid"]=fixedIncomeObj.fm_investmentid;
				_statement.parameters[":fm_type"]=fixedIncomeObj.fm_type;
				_statement.parameters[":fm_accountid"]=fixedIncomeObj.fm_accountid;
				_statement.parameters[":fm_channelid"]=fixedIncomeObj.fm_channelid;
				_statement.parameters[":fm_investmentdate"]=fixedIncomeObj.fm_investmentdate;
				_statement.parameters[":fm_percent"]=fixedIncomeObj.fm_percent;
				_statement.parameters[":fm_maturityamount"]=fixedIncomeObj.fm_maturityamount;
				_statement.parameters[":fm_investperiod"]=fixedIncomeObj.fm_investperiod;
				_statement.parameters[":fm_comments"]=fixedIncomeObj.fm_comments;
				_statement.parameters[":fm_investmentamount"]=fixedIncomeObj.fm_investmentamount;
				_statement.parameters[":fm_investmentname"]=fixedIncomeObj.fm_investmentname;
				_statement.parameters[":fm_status"]=fixedIncomeObj.fm_status;
				_statement.parameters[":fm_maturitydate"]=fixedIncomeObj.fm_maturitydate;
				_statement.execute();
				var expRecord:Object=new Object();
				if (fixedIncomeObj.type == CommonConstants.BUY)
				{
					expRecord.type=CommonConstants.BUY
				}
				else
					expRecord.type=CommonConstants.SELL
				expRecord.account=fixedIncomeObj.fm_accountid;
				expRecord.amount=fixedIncomeObj.fm_investmentamount;
				expRecord.category=CommonConstants.FIXEDINCOME_CATEGORY_ID;
				expRecord.payee=0;
				expRecord.memo="FIXED INCOME INVESTMENT";
				expRecord.date=fixedIncomeObj.fm_investmentdate;
				expRecord.exRate=1.0;
				edm.updateDependentExpense(expRecord, fixedIncomeObj.fm_investmentid, _sqlConnection);
				_sqlConnection.commit();
				_sqlConnection.close();
				loadData();
				dispatchEvent(new Event("InvestmentUpdated"));
				edm.refreshExpenseDataCache(null);
				PMLogger.log("EXPENSE", "EXPENSE UPDATED", fixedIncomeObj);
			}
			catch (sqlError:SQLError)
			{
				_sqlConnection.rollback();
				_sqlConnection.close();
				trace(sqlError.details);
			}
			return 1;
		}
		public function updatePaymentDetails(paymentObj:Object):int
		{
			var _sqlConnection:SQLConnection=CommonData.getConnection();
			try
			{
				//_sqlConnection.open();
				_sqlConnection.begin();
				deletePayment(paymentObj, _sqlConnection);
				addPropertyPayment(paymentObj);
				_sqlConnection.commit();
				_sqlConnection.close();
					//loadData();
			}
			catch (sqlError:SQLError)
			{
				_sqlConnection.rollback();
				_sqlConnection.close();
				trace(sqlError.details);
			}
			return 1;
		}
		public function updatePropertyDetails(propertyObj:Object):int
		{
			var _sqlConnection:SQLConnection=CommonData.getConnection();
			try
			{
				//_sqlConnection.open();
				var _statement:SQLStatement=new SQLStatement();
				_statement.sqlConnection=_sqlConnection;
				_sqlConnection.begin();
				_statement.text=PropertySQLScript.UPDATE_PROPERTY_DETAILS;
				_statement.parameters[":pd_propertyname"]=propertyObj.propertyName;
				_statement.parameters[":pd_developer"]=propertyObj.developer;
				_statement.parameters[":pd_size"]=propertyObj.size;
				_statement.parameters[":pd_rate"]=propertyObj.rate;
				_statement.parameters[":pd_othercharges"]=propertyObj.charges;
				_statement.parameters[":pd_remark"]=propertyObj.remark;
				_statement.parameters[":pd_propertyid"]=propertyObj.propertyid;
				_statement.execute();
				_sqlConnection.commit();
				_sqlConnection.close();
				loadData();
			}
			catch (sqlError:SQLError)
			{
				_sqlConnection.rollback();
				_sqlConnection.close();
				trace(sqlError.details);
			}
			return 1;
		}
	}
}